﻿/*
 * TabBtn - running app tab
 * that can control app focus, display,...
 * 
 * created by: asida@centrum.cz
 * 
 * initial implementation: 8.12.2011
 * last updated:
 */
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
using System.Windows.Threading;
using System.Collections.ObjectModel;

namespace uhul.Controls
{

  public partial class TabBtn : RadioButton
  {

    private bool _requestLazyResizeButton = false;
    private static bool _canResizeButton = true;
    
    /// <summary>
    /// private save new button size for lazy writer
    /// </summary>
    private double _newSize;
    //private bool _isHooked = false;
    private static DispatcherTimer timer;




    static TabBtn()
    {
      //one timer for all buttons
      timer = new DispatcherTimer();
      timer.Interval = TimeSpan.FromMilliseconds(500);
      timer.Start();
    }





    public TabBtn()
    {
      InitializeComponent();

      //this control is created automatically by binding
      //thus must hookup to init events after added to GUI
      this.Unloaded += new RoutedEventHandler(TabBtn_Unloaded);
      this.Loaded += new RoutedEventHandler(TabBtn_Loaded);

    }





    /// <summary>
    /// close button event handler
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void AppCloseClick(object sender, RoutedEventArgs e)
    {

      //_requestLazyResizeButton = true;

      //send stop command to this app itself
      XapExplorer.Commands.Add(
        new Command()
        {
          CommandType = CommandTypeEnum.StopApplication,
          TargetApplicationName = this.AppName
        }.ToJson()
      );

      //begin kill process
      //XapExplorer.StopApplication(this.AppName);

    }





    #region eventHandlers


    private void TabBtn_Loaded(object sender, System.Windows.RoutedEventArgs e)
    {

      //hookup button to XapExplorer events...
      XapExplorer.ResizeTabButtons += new XapExplorer.ResizeTabButtonEventArgs(resizeTabButton);
      //this.Width = XapExplorer.ComputedTabButtonWidth;

      //init lazy resizer...
      _newSize = XapExplorer.ComputedTabButtonWidth;
      _requestLazyResizeButton = true;

      //hookup button to its timer event
      TabBtn.timer.Tick += new EventHandler(doLazyResize);
    }




    private void TabBtn_Unloaded(object sender, System.Windows.RoutedEventArgs e)
    {
      XapExplorer.ResizeTabButtons -= new XapExplorer.ResizeTabButtonEventArgs(resizeTabButton);
      TabBtn.timer.Tick -= new EventHandler(doLazyResize);

      //if (XapExplorer.RunningApplications.Count == 0)
      //unloaded control never sends mouseLeave event
      //so reset _canResizeButton here
      _canResizeButton = true;
    }




    /// <summary>
    /// resize tab button call from XapExplorer
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void resizeTabButton(object sender, ResizeEventArgs e)
    {
      if (_canResizeButton)
        _refreshGUI(e.NewWidth);

      else
      {
        _newSize = e.NewWidth;
        _requestLazyResizeButton = true;
      }

      //if (!_requestLazyResizeButton)
      //  _refreshGUI(e.NewWidth);
      //else
      //  _newSize = e.NewWidth;

    }





    /// <summary>
    /// lazy resize event handler
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void doLazyResize(object sender, EventArgs e)
    {
      //_refreshGUI(XapExplorer.AppTabsControl.ActualWidth, XapExplorer.RunningApplications.Count);
      if (_requestLazyResizeButton && _canResizeButton)
      {
        _refreshGUI(_newSize);
        _requestLazyResizeButton = false;
      }
    }




    //private void zmenaPoctuAplikaci(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    //{
    //  ReadOnlyObservableCollectionPlus<InteractiveApp> s = (ReadOnlyObservableCollectionPlus<InteractiveApp>)sender;
    //  //_refreshGUI(this.AppDisplayManager.DrivingWidthCtl.ActualWidth, s.Count);
    //  _requestResizeButton = true;
    //  //_refreshGUI(XapExplorer.AppTabsControl.ActualWidth, s.Count);
    //}




    private void mouseEnter(object sender, RoutedEventArgs e)
    {
      _canResizeButton = false;
      //timer.Stop();

    }






    private void mouseLeave(object sender, RoutedEventArgs e)
    {
      _canResizeButton = true;

      //if (_requestLazyResizeButton)
      //{
      //  timer.Start();
      //}

      //_refreshGUI(_newSize);
      //_requestLazyResizeButton = false;
    }


    

    #endregion eventHandlers




    #region AppName



    public static readonly DependencyProperty AppNameProperty =
      DependencyProperty.Register("AppName", typeof(string),
      typeof(TabBtn), new PropertyMetadata(null, new PropertyChangedCallback(onAppNameChanged)));


    private static void onAppNameChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {

      //TabBtn tbtn = (TabBtn)d;

      //if (!tbtn._isHooked)
      //{
      //  tbtn._hookUp();
      //  tbtn._refreshGUI(XapExplorer.AppTabsControl.ActualWidth, XapExplorer.RunningApplications.Count);
      //}
      
      //if (tbtn.AppName == null)
      //  return;

      //string tmpVal = (string)e.NewValue;

    }




    /// <summary>
    /// Name of application that is running under current button
    /// </summary>
    public string AppName
    {
      get { return (string)GetValue(AppNameProperty); }
      set { SetValue(AppNameProperty, value); }
    }


    #endregion AppName




    //#region AktivniAplikace

    //private static void onIsActiveChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    //{
    //  //TabBtn tbtn = (TabBtn)d;

    //  //if (tbtn.AppName == null)
    //  //  return;

    //  //string tmpVal = (string)e.NewValue;

    //}

    //public static readonly DependencyProperty IsActiveProperty =
    //  DependencyProperty.Register("IsActive", typeof(bool),
    //  typeof(TabBtn), new PropertyMetadata(false, new PropertyChangedCallback(onIsActiveChanged)));

    ///// <summary>
    ///// Stack
    ///// </summary>
    //public bool IsActive
    //{
    //  get { return (bool)GetValue(IsActiveProperty); }
    //  set
    //  {
    //    SetValue(IsActiveProperty, value);
    //  }
    //}

    //#endregion AktivniAplikace







    ///// <summary>
    ///// zmena aktivni aplikace v AppDisplayManager
    ///// </summary>
    ///// <param name="sender"></param>
    ///// <param name="e"></param>
    //private void TabBtn_Click(object sender, RoutedEventArgs e)
    //{
    //  this.AppDisplayManager.ChangeActiveApplication(this.AppName);
    //}






    //private void _refreshGUI(double vportWidth, int numItems)
    private void _refreshGUI(double newTabBtnWidth)
    {

      //if (vportWidth == 0 || numItems == 0)
      //  return;
      if (newTabBtnWidth == 0)
        return;

      //if (this.RenderSize.Width < this.MaxWidth)

      //double newWidth = vportWidth / (double)numItems;
      //double origWidth = this.DesiredSize.Width;
      double origWidth = this.RenderSize.Width;

      if (newTabBtnWidth > this.MaxWidth)
        newTabBtnWidth = this.MaxWidth;

      if (newTabBtnWidth == origWidth)
        return;

      //VisualStateManager.GoToState(this, "StretchWidth", true);
      //Storyboard myStoryboard = (Storyboard)(this.FindName("stretchWidth"));
      //Storyboard myStoryboard = this.stretchWidth;
      Storyboard s = (Storyboard)this.Resources["stretchWidth"];

      DoubleAnimationUsingKeyFrames f = (DoubleAnimationUsingKeyFrames)s.Children[0];

      //SplineDoubleKeyFrame k1 = (SplineDoubleKeyFrame)(this.FindName("startStretchWidthFrame"));
      //SplineDoubleKeyFrame k1 = this.startStretchWidthFrame;
      SplineDoubleKeyFrame k1 = (SplineDoubleKeyFrame)f.KeyFrames[0];
      k1.Value = this.RenderSize.Width;
      //k1.Value = this.DesiredSize.Width;
  
      //SplineDoubleKeyFrame k2 = (SplineDoubleKeyFrame)(this.FindName("endStretchWidthFrame"));
      //SplineDoubleKeyFrame k2 = this.endStretchWidthFrame;
      SplineDoubleKeyFrame k2 = (SplineDoubleKeyFrame)f.KeyFrames[1];
      k2.Value = newTabBtnWidth;

      s.Begin();
    }


  }

}
